#include "addframe.h"
#include "ui_addframe.h"

AddFrame::AddFrame(QWidget *parent) :
    QDialog(parent),
    ui(new Ui::AddFrame)
{
    ui->setupUi(this);

    table = TD_ARTICLE;

    siteDialog=nullptr;
    ui->btn_ref->setEnabled(false);
}

AddFrame::~AddFrame()
{
    delete ui;
}

void AddFrame::setSection(const Section &section)
{
    pSection=section;
    setWindowTitle(pSection.name);
}

void AddFrame::setItem(const Frame &item)
{
    pItem=item;
    ui->title->setText(pItem.title);
    ui->subtitle->setPlainText(pItem.subtitle);
    ui->prompt->setPlainText(pItem.prompt);
    ui->btn_ref->setEnabled(true);
    ui->btn_submit->setText("保存");
}

bool AddFrame::addItem(const Frame &item)
{
    QSqlQuery query;
    query.prepare(QString("insert into %1 (section_id,seq,title,subtitle,prompt) values (?,?,?,?,?)")
                  .arg(table));
    query.addBindValue(pSection.id);
    query.addBindValue(item.seq);
    query.addBindValue(item.title);
    query.addBindValue(item.subtitle);
    query.addBindValue(item.prompt);

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

bool AddFrame::updateItem(const Frame &item)
{
    QSqlQuery query;
    query.prepare(QString("update %1 set title=?,subtitle=?,prompt=? where id=%2")
                  .arg(table)
                  .arg(item.id));
    query.addBindValue(item.title);
    query.addBindValue(item.subtitle);
    query.addBindValue(item.prompt);

    /*
    auto sql=QString("update %1 set title='%2',subtitle='%3',prompt='%4' where id=%5")
            .arg(table)
            .arg(item.title)
            .arg(item.subtitle)
            .arg(item.prompt)
            .arg(item.id);
    if(query.exec(sql))
        return true;
    */

    if(query.exec())
        return true;
    else
    {
        qDebug() << query.lastError().text();
        return false;
    }
}

void AddFrame::on_btn_submit_clicked()
{
    Frame item;
    item.id=pItem.id;
    item.title=ui->title->text().trimmed();
    item.subtitle=ui->subtitle->toPlainText().trimmed();
    item.prompt=ui->prompt->toPlainText().trimmed();

    if(!item.isValid())
    {
        MESSAGE_DETAIL_EMPTY
    }

    if(pItem.id == 0)
    {
        if(addItem(item))
        {
            add(QString::number(item.seq),item.title);
            accept();
        }
        else
            MESSAGE_CANNOT_SUBMIT
    }
    else
    {
        if(pItem.isEqual(item))
        {
            MESSAGE_NOT_CHANGE
        }

        if(updateItem(item))
            accept();
        else
            MESSAGE_CANNOT_SUBMIT
    }
}


void AddFrame::on_btn_ref_clicked()
{
    if(pItem.id == 0)
        return;

    if(siteDialog == nullptr)
        siteDialog=new SiteDialog(this);

    siteDialog->setId(pItem.id);
    siteDialog->show();
}

